<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Model\BalanceOrder;
use App\Model\Bill;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\Order;
use App\Model\RefundHistory;
use App\Model\RefundLog;
use App\Model\Station;
use App\Model\User;
use App\Services\BankService;
use App\Services\Iot\IotService1 as IotService;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;

class OrderController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Order $order;

    #[Inject]
    protected BalanceOrder $balanceOrder;

    #[Inject]
    protected ChargeOption $chargeOption;

    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected Device $device;

    #[Inject]
    protected Admin $admin;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }


    /**导出订单
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function exportOrder(RequestInterface $request)
    {
        $page = $request->inputs(['page', 'limit', 'address', 'out_ord_id',
            'distributor_id', 'keyword', 'sn', 'time', 'payment_type', 'is_drawer',
            'status', 'min_power', 'max_power', 'channel_number']);
        $data['list'] = Db::table('orders as o')
            ->leftJoin('stations as s', 'o.station_id', '=', 's.id')
            ->leftJoin('users as u', 'o.user_id', '=', 'u.id')
            ->where(function ($query) use ($page) {
                if (array_key_exists('keyword', $page) && $page['keyword']) {
                    $query->where('o.number', 'like', '%' . $page['keyword'] . '%');
//                $query->orWhere('o.out_ord_id', 'like', '%'.$page['keyword'].'%');
                }
                if ($page['distributor_id']) {
                    $query->where('o.distributor_id', $page['distributor_id']);
                }
                if ($page['out_ord_id']) {
                    $query->where('o.out_ord_id', $page['out_ord_id']);
                }
                if ($page['payment_type']) {
                    $query->where('o.payment_type', $page['payment_type']);
                }
                if ($page['address']) {
                    $query->where('s.address', '%' . $page['address'] . '%');
                }
                if ($page['sn']) {
                    $query->where('o.sn', $page['sn']);
                }
                if ($page['status']) {
                    $query->where('o.status', $page['status']);
                }
                if ($page['min_power']) {
                    $query->where('o.power', '>=', $page['min_power']);
                }
                if ($page['max_power']) {
                    $query->where('o.power', '<=', $page['max_power']);
                }
                if ($page['channel_number']) {
                    $query->where('o.channel_number', $page['channel_number']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
            })->orderBy('o.id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->select('o.id', 'o.number', 'o.sn', 'o.channel_number', 'o.minutes',
                'o.is_check', 'o.duration_seconds', 'o.fee', 'o.power_fee', 'o.return_fee', 'o.is_return_fee',
                'o.original_fee', 'o.service_fee', 'o.status',
                'o.power', 'o.estimate_stop_at', 'o.stop_at', 'o.stop_reason', 'o.payment_type',
                'o.out_ord_id', 'o.charge_id','o.coupon_record_id',
                's.address', 's.name as station_name',
                'u.nickname', 'o.is_autoload')
            ->get();
        $data['list'] = json_encode($data['list']);
        $data['list'] = json_decode($data['list'],true);
        try{
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            // 设置 Excel 文档的头部
            $sheet->setCellValue('A1', '订单号');
            $sheet->setCellValue('B1', '充电人');
            $sheet->setCellValue('C1', '充电开始时间');
            $sheet->setCellValue('D1', '充电结束时间');
            $sheet->setCellValue('E1', '功率');
            $sheet->setCellValue('F1', '实付金额/元');
            $sheet->setCellValue('G1', '退款金额/元');
            $sheet->setCellValue('H1', '实收金额/元');
            $sheet->setCellValue('I1', '是否使用券');
//        $sheet->setCellValue('J1', '交易单号');
            $sheet->setCellValue('J1', '电站名称');
            $sheet->setCellValue('K1', '设备号');
            $sheet->setCellValue('L1', '端口');
            $sheet->setCellValue('M1', '支付类型');
            $sheet->setCellValue('N1', '停止原因');
            foreach (range('A', 'O') as $columnID) {
                $sheet->getColumnDimension($columnID)->setAutoSize(true);
            }

// 设置单元格水平居中的样式数组配置
            $styleArray = [
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                ],
            ];

// 应用样式到第一行的A到O列
            $sheet->getStyle('A:O')->applyFromArray($styleArray);
            // 从第二行开始填充订单数据
            $row = 2;
            foreach ($data['list'] as $order) {
                switch($order['payment_type']){
                    case 'wx_lite':
                        $order['payment_type'] = '微信';
                        break;
                    case 'balance':
                        $order['payment_type'] = '余额';
                        break;
                    default:
                        $order['payment_type'] = '支付宝';
                        break;
                }
                $sheet->setCellValue('A' . $row, $order['number'] . ' ');
                $sheet->setCellValue('B' . $row, $order['nickname']);
                $sheet->setCellValue('C' . $row, $order['estimate_stop_at']);
                $sheet->setCellValue('D' . $row, $order['stop_at']);
                $sheet->setCellValue('E' . $row, $order['power']);
                $sheet->setCellValue('F' . $row, $order['power_fee']);
                $sheet->setCellValue('G' . $row, $order['return_fee']);
                $sheet->setCellValue('H' . $row, number_format($order['power_fee'] - $order['return_fee'], 2));
                if ($order['coupon_record_id']) {
                    $sheet->setCellValue('I' . $row, '是');
                } else {
                    $sheet->setCellValue('I' . $row, '否');
                }
//            $sheet->setCellValue('J' . $row, $order['out_ord_id'].' ');
                $sheet->setCellValue('J' . $row, $order['station_name']);
                $sheet->setCellValue('K' . $row, $order['sn']);
                $sheet->setCellValue('L' . $row, $order['channel_number']);
                $sheet->setCellValue('M' . $row, $order['payment_type']);
                $sheet->setCellValue('N' . $row, $order['stop_reason']);
                $row++;
            }
            // 将 Spreadsheet 对象写入 XLSX 文件
            $writer = new Xlsx($spreadsheet);
            // 创建临时文件
            $publicPath = BASE_PATH . '/public/upload/xls/';
            $fileName = date('YmdHis', time()) . '-orders.xlsx';
//        $temp_file = tempnam(sys_get_temp_dir(), $fileName);
            $temp_file = $publicPath . $fileName;
            // 保存到临时文件
            $writer->save($temp_file);
            return $this->success(['url' => Common::MAIN_HOST . '/upload/xls/' . $fileName]);

        }catch (\Exception $e){
            return $this->error(1001,$e->getMessage());
        }

    }

    /**订单列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request): ResponseInterface
    {
        $info = $this->admin->getInfo($request);
        $page = $request->inputs(['page', 'limit', 'address', 'out_ord_id',
            'distributor_id', 'keyword', 'sn', 'time', 'payment_type',
            'status', 'min_power', 'max_power', 'channel_number']);
        $data['list'] = Db::table('orders as o')
            ->leftJoin('stations as s', 'o.station_id', '=', 's.id')
            ->leftJoin('users as u', 'o.user_id', '=', 'u.id')
            ->leftJoin('service as v', 'o.service_id', '=', 'v.id')
            ->where(function ($query) use ($page, $info) {
                if (array_key_exists('keyword', $page) && $page['keyword']) {
                    $query->where('o.number', 'like', '%' . $page['keyword'] . '%');
//                $query->orWhere('o.out_ord_id', 'like', '%'.$page['keyword'].'%');
                }
                if ($page['distributor_id']) {
                    $query->where('o.distributor_id', $page['distributor_id']);
                }
                if ($page['out_ord_id']) {
                    $query->where('o.out_ord_id', $page['out_ord_id']);
                }
                if ($page['payment_type']) {
                    $query->where('o.payment_type', $page['payment_type']);
                }
                if ($page['address']) {
                    $query->where('s.address', '%' . $page['address'] . '%');
                }
                if ($page['sn']) {
                    $query->where('o.sn', $page['sn']);
                }
                if ($page['status']) {
                    $query->where('o.status', $page['status']);
                }
                if ($page['min_power']) {
                    $query->where('o.power', '>=', $page['min_power']);
                }
                if ($page['max_power']) {
                    $query->where('o.power', '<=', $page['max_power']);
                }
                if ($page['channel_number']) {
                    $query->where('o.channel_number', $page['channel_number']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
            })->orderBy('o.id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->select('o.id','o.number','o.sn','o.channel_number','o.minutes',
                'o.is_check','o.duration_seconds','o.fee','o.power_fee','o.return_fee','o.is_return_fee',
                'o.original_fee','o.status',
                'o.power','o.estimate_stop_at','o.stop_at','o.stop_reason','o.payment_type',
                'o.out_ord_id','o.charge_id',
                's.address', 's.name as station_name',
                'u.nickname', 'v.name as service_name')
            ->get();
//        $data['list'] = json_encode($data['list']);
//        $data['list'] = json_decode($data['list'], true);
//        foreach ($data['list'] as $k => $v) {
//            $data['list'][$k]['distributor_history'] = Db::table('bills as b')
//                ->leftJoin('distributors as d', 'b.account_id', '=', 'd.id')
//                ->where('b.account_type', 'App\Model\Distributors')
//                ->where('b.target_id', $v['id'])
//                ->select('b.*', 'd.name', 'd.level')
//                ->get();
//        }
        $data['total'] = Db::table('orders as o')
            ->leftJoin('stations as s', 'o.station_id', '=', 's.id')
            ->leftJoin('users as u', 'o.user_id', '=', 'u.id')
            ->leftJoin('service as v', 'o.service_id', '=', 'v.id')
            ->where(function ($query) use ($page, $info) {
                if (array_key_exists('keyword', $page) && $page['keyword']) {
                    $query->where('o.number', 'like', '%' . $page['keyword'] . '%');
//                    $query->orWhere('o.out_ord_id', 'like', '%'.$page['keyword'].'%');
                }
                if ($page['out_ord_id']) {
                    $query->where('o.out_ord_id', $page['out_ord_id']);
                }
                if ($page['distributor_id']) {
                    $query->where('o.distributor_id', $page['distributor_id']);
                }
                if ($page['address']) {
                    $query->where('s.address', '%' . $page['address'] . '%');
                }
                if ($page['payment_type']) {
                    $query->where('o.payment_type', $page['payment_type']);
                }
                if ($page['sn']) {
                    $query->where('o.sn', $page['sn']);
                }
                if ($page['status']) {
                    $query->where('o.status', $page['status']);
                }
                if ($page['min_power']) {
                    $query->where('o.power', '>=', $page['min_power']);
                }
                if ($page['max_power']) {
                    $query->where('o.power', '<=', $page['max_power']);
                }
                if ($page['channel_number']) {
                    $query->where('o.channel_number', $page['channel_number']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
            })->count();
        return $this->success($data);
    }

    /**获取折线图数据
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getChart(RequestInterface $request): ResponseInterface
    {
        $keys = [];
        $page = $request->inputs(['page', 'limit', 'address', 'out_ord_id',
            'distributor_id', 'keyword', 'sn', 'time', 'payment_type',
            'min_power', 'max_power', 'channel_number']);
        $data = [];
        $total['powerfee'] = 0;
        $total['returnfee'] = 0;
        $total['servicefee'] = 0;
        $total['selffee'] = 0;
        $time = $page['time'];
        if (isset($time) && $time) {
            $start_date = new \DateTime($time[0]);
            $end_date = new \DateTime($time[1]);
            $interval = $start_date->diff($end_date);
            $days = $interval->days;
            for ($i = 0; $i < $days; $i++) {
                // 从起始日期增加天数
                $current_date = (clone $start_date)->modify("+{$i} day");
                // 执行所需的操作，例如打印每天的日期
                $now_date = $current_date->format('Y-m-d');
                $keys[] = $now_date;
                $powerfee = Db::table('orders as o')
                    ->leftJoin('stations as s', 'o.station_id', '=', 's.id')
                    ->where(function ($query) use ($page, $now_date) {
                        if (array_key_exists('keyword', $page) && $page['keyword']) {
                            $query->where('o.number', 'like', '%' . $page['keyword'] . '%');
                        }
                        if ($page['distributor_id']) {
                            $query->where('o.distributor_id', $page['distributor_id']);
                        }
                        if ($page['out_ord_id']) {
                            $query->whereIn('o.out_ord_id', $page['out_ord_id']);
                        }
                        if ($page['payment_type']) {
                            $query->where('o.payment_type', $page['payment_type']);
                        }
                        if ($page['address']) {
                            $query->where('s.address', '%' . $page['address'] . '%');
                        }
                        if ($page['sn']) {
                            $query->where('o.sn', $page['sn']);
                        }
                        $query->whereIn('o.status', [Order::STATUS_REFUNDED, Order::STATUS_END]);
                        if ($page['min_power']) {
                            $query->where('o.power', '>=', $page['min_power']);
                        }
                        if ($page['max_power']) {
                            $query->where('o.power', '<=', $page['max_power']);
                        }
                        if ($page['channel_number']) {
                            $query->where('o.channel_number', $page['channel_number']);
                        }
                        $query->where('o.created_at', '>=', $now_date . ' 00:00:00');
                        $query->where('o.created_at', '<=', $now_date . ' 23:59:59');
                    })->sum('o.fee');
                $total['powerfee'] += $powerfee;
                $returnfee = Db::table('orders as o')
                    ->leftJoin('stations as s', 'o.station_id', '=', 's.id')
                    ->where(function ($query) use ($page, $now_date) {
                        if (array_key_exists('keyword', $page) && $page['keyword']) {
                            $query->where('o.number', 'like', '%' . $page['keyword'] . '%');
                        }
                        if ($page['distributor_id']) {
                            $query->where('o.distributor_id', $page['distributor_id']);
                        }
                        if ($page['out_ord_id']) {
                            $query->whereIn('o.out_ord_id', $page['out_ord_id']);
                        }
                        if ($page['payment_type']) {
                            $query->where('o.payment_type', $page['payment_type']);
                        }
                        if ($page['address']) {
                            $query->where('s.address', '%' . $page['address'] . '%');
                        }
                        if ($page['sn']) {
                            $query->where('o.sn', $page['sn']);
                        }
                        $query->whereIn('o.status', [Order::STATUS_REFUNDED, Order::STATUS_END]);
                        if ($page['min_power']) {
                            $query->where('o.power', '>=', $page['min_power']);
                        }
                        if ($page['max_power']) {
                            $query->where('o.power', '<=', $page['max_power']);
                        }
                        if ($page['channel_number']) {
                            $query->where('o.channel_number', $page['channel_number']);
                        }
                        $query->where('o.created_at', '>=', $now_date . ' 00:00:00');
                        $query->where('o.created_at', '<=', $now_date . ' 23:59:59');
                    })->sum('o.return_fee');
                $total['returnfee'] += $returnfee;
                $servicefee = Db::table('orders as o')
                    ->leftJoin('stations as s', 'o.station_id', '=', 's.id')
                    ->where(function ($query) use ($page, $now_date) {
                        if (array_key_exists('keyword', $page) && $page['keyword']) {
                            $query->where('o.number', 'like', '%' . $page['keyword'] . '%');
                        }
                        if ($page['distributor_id']) {
                            $query->where('o.distributor_id', $page['distributor_id']);
                        }
                        if ($page['out_ord_id']) {
                            $query->whereIn('o.out_ord_id', $page['out_ord_id']);
                        }
                        if ($page['payment_type']) {
                            $query->where('o.payment_type', $page['payment_type']);
                        }
                        if ($page['address']) {
                            $query->where('s.address', '%' . $page['address'] . '%');
                        }
                        if ($page['sn']) {
                            $query->where('o.sn', $page['sn']);
                        }
                        $query->whereIn('o.status', [Order::STATUS_REFUNDED, Order::STATUS_END]);
                        if ($page['min_power']) {
                            $query->where('o.power', '>=', $page['min_power']);
                        }
                        if ($page['max_power']) {
                            $query->where('o.power', '<=', $page['max_power']);
                        }
                        if ($page['channel_number']) {
                            $query->where('o.channel_number', $page['channel_number']);
                        }
                        $query->where('o.created_at', '>=', $now_date . ' 00:00:00');
                        $query->where('o.created_at', '<=', $now_date . ' 23:59:59');
                    })->sum('o.service_fee');
                $total['servicefee'] += $servicefee;

                $total['selffee'] += 0;
                $data['actualData'][] = $returnfee;
                $data['expectedData'][] = $powerfee;
                $data['serviceData'][] = $servicefee;
                $data['selfData'][] = 0;
            }
        }
        $data['list'] = $data;
        $data['key'] = $keys;
        $data['total'] = $total;
        return $this->success($data);
    }

    /**余额充值订单
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function balanceList(RequestInterface $request): ResponseInterface
    {
        $page = $request->inputs(['page', 'limit', 'out_ord_id',
            'distributor_id', 'keyword', 'time', 'payment_type',
            'status']);
        $inDevice = [];
        if ($page['distributor_id']) {
            $level = $this->distributors->where('id', $page['distributor_id'])->value('level');
            if ($level == Distributors::LEVEL_1) {
                $devices = $this->device
                    ->where('distributor_id', $page['distributor_id'])->get(['id'])
                    ->toArray();
            } else {
                $devices = $this->device
                    ->where('child_distributor_id', $page['distributor_id'])->get(['id'])
                    ->toArray();
            }
            foreach ($devices as $k => $v) {
                $inDevice[] = $v['id'];
            }
        }
        $data['list'] = Db::table('balance_orders as o')
            ->leftJoin('users as u', 'o.user_id', '=', 'u.id')
            ->where(function ($query) use ($page, $inDevice) {
                if (array_key_exists('keyword', $page) && $page['keyword']) {
                    $query->where('o.number', 'like', '%' . $page['keyword'] . '%');
//                $query->orWhere('o.out_ord_id', 'like', '%'.$page['keyword'].'%');
                }
                if ($page['out_ord_id']) {
                    $query->where('o.out_ord_id', $page['out_ord_id']);
                }
                if ($page['distributor_id']) {
                    $query->whereIn('o.device_id', $inDevice);
                }
                if ($page['payment_type']) {
                    $query->where('o.payment_type', $page['payment_type']);
                }
                if ($page['status']) {
                    $query->where('o.status', $page['status']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
            })->orderBy('o.id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->select('o.*', 'u.nickname')
            ->get();
        $data['total'] = Db::table('balance_orders as o')
            ->leftJoin('users as u', 'o.user_id', '=', 'u.id')
            ->where(function ($query) use ($page, $inDevice) {
                if (array_key_exists('keyword', $page) && $page['keyword']) {
                    $query->where('o.number', 'like', '%' . $page['keyword'] . '%');
//                    $query->orWhere('o.out_ord_id', 'like', '%'.$page['keyword'].'%');
                }
                if ($page['distributor_id']) {
                    $query->whereIn('o.device_id', $inDevice);
                }
                if ($page['payment_type']) {
                    $query->where('o.payment_type', $page['payment_type']);
                }
                if ($page['status']) {
                    $query->where('o.status', $page['status']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
            })->count();
        return $this->success($data);
    }


    /**下拉菜单-套餐
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function selectCharge(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $distributor_id = $request->input('distributor_id');
        $list = $this->chargeOption->where('distributor_id', 0)->orderBy('sort', 'desc')
            ->get(['id', 'name'])->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['name'] = '[默认]' . $v['name'];
        }
        if ($distributor_id) {
            $distributor_id = json_decode($distributor_id);
            if (count($distributor_id) > 0) {
                $distributor_id = end($distributor_id);
                $dis_list = $this->chargeOption->where('distributor_id', $distributor_id)->orderBy('sort', 'desc')
                    ->get(['id', 'name'])->toArray();
                $list = array_merge($list, $dis_list);
            }
        }
        return $this->success($list);
    }

    /**下拉菜单充电桩
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function selectStation(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $distributor_id = $request->input('distributor_id');
        if (!$distributor_id) {
            return $this->error(code: 1001, msg: '请先选择经销商');
        }
        $distributor_id = json_decode($distributor_id);
        if (is_array($distributor_id)) {
            if (count($distributor_id) > 0) {
                $distributor_id = end($distributor_id);
            }
        }
        $list = $this->station->where('distributor_id', $distributor_id)
            ->get(['id', 'name'])->toArray();
        return $this->success($list);
    }

    /**修改状态
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function changeStatus(RequestInterface $request): ResponseInterface
    {
        $status = $request->input('status', 0, 'int');
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(code: 1001, msg: '缺失参数id');
        }
        $this->station->where('id', $id)->update(['is_active' => $status]);
        return $this->success(msg: '修改成功');
    }


    /**获取经销商id
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getDistributor(RequestInterface $request): ResponseInterface
    {
        $station_id = $request->input('station_id', 0, 'int');
        $distributorId = $this->station->where('id', $station_id)->first(['distributor_id']);
        return $this->success($distributorId);
    }


    /**创建电站
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $data = $request->post();
        if (!$data['distributor_id']) {
            $data['distributor_id'] = 0;
        }
        if ($data['images']) {
            $data['images'] = json_encode($data['images']);
        }
        if (array_key_exists('id', $data) && $data['id'] > 0) {
            $id = $data['id'];
            unset($data['id']);
            if (isset($data['distributor_name'])) {
                unset($data['distributor_name']);
            }
            if (isset($data['device_num'])) {
                unset($data['device_num']);
            }
            if (is_array($data['distributor_id'])) {
                $data['distributor_id'] = end($data['distributor_id']);
            }
            if (array_key_exists('updated_at', $data)) {
                unset($data['updated_at']);
            }
            $this->station->where('id', $id)->update($data);
        } else {
            $data['distributor_id'] = end($data['distributor_id']);
            Station::create($data);
        }
        return $this->success();
    }

    /**删除充电站
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        $this->station->where('id', $id)->delete();
        return $this->success();
    }

    /**关闭订单
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function stopOrder(RequestInterface $request): ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        $orderModel = $this->order->find($id);
        if ($orderModel->is_check == 0 || $orderModel->status == Order::STATUS_PAID) {
            $orderModel->fail('远程断电', true);
        } else {
            $orderModel->stop('远程断电', $orderModel->surplus_electricitys, true);
        }
        return $this->success();
    }

    /**
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function refundService(RequestInterface $request): ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        $orderModel = $this->order->find($id);
        if ($orderModel->service_fee > 0) {
            $orderModel->serviceRefund();
        }
        return $this->success();
    }


    /**获取退款记录
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function getRefundList(RequestInterface $request):ResponseInterface{
        $number= $request->input('number');
        $type = $request->input('type');
        $list = RefundLog::where('number',$number)
            ->where('type',$type)
            ->get();
        return $this->success($list);
    }


    public function refundBalance(RequestInterface $request): ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        $fee = $request->input('fee', 0);
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        if ($fee <= 0) {
            return $this->error(1002, '参数错误');
        }
        $orderModel = $this->balanceOrder->find($id);
        if($fee + $orderModel->return_fee > $orderModel->fee){
            return $this->error(1002, '订单可退款金额为'.$orderModel->fee-$orderModel->return_fee.'元');
        }
        $user = User::where('id',$orderModel->user_id)->first();
        if($user->balance < $fee){
            return $this->error(1002, '用户余额仅剩'.$user->balance.'元');
        }
        $user = User::where('id', $orderModel->user_id)->first();
        $normal = new Normal();
        $data['openid'] = $user->openid;
        $data['number'] = $orderModel->number;
        $data['order_id'] = $orderModel->out_ord_id;
        $data['refund_no'] ='BF'.$normal->randOrder($orderModel->id);
        $data['type'] =  2;
        $data['fee'] = $fee;
        $bankService = new BankService();
        $result = $bankService->refund($data);
        if($result['return_code'] == 0){
            $orderModel->return_fee += $fee;
            $orderModel->status = Order::STATUS_REFUNDED;
            $orderModel->save();
            $user->balance -= $fee;
            $user->save();
        }else{
            return $this->error(1001,$result['return_msg']);
        }
        return $this->success();
    }

    /**常规退款
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function refundNormal(RequestInterface $request): ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        $fee = $request->input('fee', 0);
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        if ($fee <= 0) {
            return $this->error(1002, '参数错误');
        }
        $orderModel = $this->order->find($id);
        if ($orderModel->is_return_fee == 0) {
            $orderModel->return_fee = 0;
            $orderModel->save();
        }
        if ($orderModel && $orderModel->return_fee + $fee <= $orderModel->fee) {
            $normal = new Normal();
            $data['openid'] = $orderModel->user->openid;
            $data['number'] = $orderModel->number;
            $data['order_id'] = $orderModel->out_ord_id;
            $data['refund_no'] ='RF'.$normal->randOrder($orderModel->device_id);
            $data['type']  =  1;
            $data['fee'] = $fee;
            if($orderModel->payment_type == Bill::PAYMENT_TYPE_BALANCE){
                $data['refund_no'] ='余额退款';
                $orderModel->is_return_fee = 1;
                $orderModel->return_fee += $fee;
                $orderModel->status = Order::STATUS_REFUNDED;
                $orderModel->save();
                $orderModel->user->balance+=$fee;
                $orderModel->normalRefundSuccess($data);
                $save['refund_no'] =  $data['refund_no'];
                $save['number'] = $orderModel->number;
                $save['type'] = 1;
                $save['status'] = 1;
                $save['refund_time'] = date('Y-m-d H:i:s');
                $save['reject_amt'] = $fee*100;
                RefundLog::create($save);
            }else{
                $data['refund_no'] ='RF'.$normal->randOrder($orderModel->device_id);
                $bankService = new BankService();
                $result = $bankService->refund($data);
                if($result['return_code'] == 0){
                    $orderModel->is_return_fee = 1;
                    $orderModel->return_fee += $fee;
                    $orderModel->status = Order::STATUS_REFUNDED;
                    $orderModel->save();
                    $orderModel->normalRefundSuccess($data);
                }else{
                    return $this->error(1002, $result['return_msg']);
                }
            }
            $allKey = 'ALL_ORDER_PROFIT';
            $this->redis->incrByFloat($allKey,-((float)$fee));

        } else {
            if ($orderModel) {
                return $this->error(1002, '当前剩余可退款金额为' . $orderModel->fee - $orderModel->return_fee . '元');
            } else {
                return $this->error(1002, '参数错误');
            }
        }
        return $this->success();
    }


    /**取消抽单
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function cancelDraw(RequestInterface $request): ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        try {
            $orderModel = $this->order->find($id);
            $orderModel->save();
            if ($orderModel->status == Order::STATUS_END || $orderModel->status == Order::STATUS_REFUNDED) {
                $orderModel->distributorSettle();
                $orderModel->feeStatics();
            }
            return $this->success(msg: '取消抽单成功');
        } catch (\Exception $e) {
            return $this->error(1001, $e->getMessage());
        }
    }
}
